﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Portals;

namespace HeroldIT.Dnn.Modules.News
{
    public class NewsCoreController : NewsController, IPortable
    {
        #region Implementation of IPortable

        public string ExportModule(int ModuleID)
        {
            IList<NewsEntry> entries = DataProvider.Instance.ExportNewsEntries(ModuleID);

            if (entries.Count > 0)
            {
                XElement export = 
                    new XElement("heroldit.news",
                        entries.Select(e => e.Export())
                    );
                return export.ToString();
            }

            return String.Empty;
        }

        private void ImportAnnouncements(int moduleId, XContainer toImport)
        {
            HttpContext context = HttpContext.Current;
            PortalSettings portalSettings = PortalController.GetCurrentPortalSettings();
            ModuleController mc = new ModuleController();
            ModuleInfo mi = mc.GetModule(moduleId, portalSettings.ActiveTab.TabID);
            this.Module = new NewsCoreSettingsProvider(mi);
            toImport.Elements("Announcement")
                .All(e =>
                         {
                             NewsEntry entry = NewsEntry.ImportAnnouncement(moduleId, e);
                             if (null != entry)
                             {
                                 NewsEntryDetail detail = entry.Details[0];
                                 if (!String.IsNullOrEmpty(detail.DetailImageUrl))
                                 {
                                     if (File.Exists(context.Server.MapPath(detail.DetailImageUrl)))
                                     {
                                         string directory = VirtualPathUtility.GetDirectory(detail.DetailImageUrl);
                                         string fileName = VirtualPathUtility.GetFileName(detail.DetailImageUrl);
                                         string extension = VirtualPathUtility.GetExtension(detail.DetailImageUrl);
                                         string destinationUrl = directory + fileName.Substring(0, fileName.Length - extension.Length)
                                                                 + ".import" + extension;
                                         string sourcePath = context.Server.MapPath(detail.DetailImageUrl);
                                         string destinationPath = Path.Combine(Path.GetDirectoryName(sourcePath),
                                                                               Path.GetFileNameWithoutExtension(
                                                                                   sourcePath) + ".import"
                                                                               + Path.GetExtension(sourcePath));
                                         string teaserPath = Path.Combine(Path.GetDirectoryName(sourcePath),
                                                                          Path.GetFileNameWithoutExtension(sourcePath)
                                                                          + ".teaser"
                                                                          + Path.GetExtension(sourcePath));
                                         string teaserUrl = directory
                                                            + fileName.Substring(0, fileName.Length - extension.Length)
                                                            + ".teaser" + extension;
                                         File.Copy(sourcePath, destinationPath, true);
                                         this.ResizeDetailImage(destinationUrl);
                                         File.Copy(sourcePath, teaserPath, true);
                                         this.ResizeTeaserImage(teaserUrl);
                                         detail.DetailImageUrl = destinationUrl;
                                         detail.TeaserImageUrl = teaserUrl;
                                         detail.TeaserImageCaption = detail.DetailImageCaption;
                                     }
                                 }
                                 DataProvider.Instance.StoreNewsEntry(moduleId, entry);
                             }
                             return true;
                         });
        }

        public void ImportModule(int ModuleID, string Content, string Version, int UserID)
        {
            try
            {
                XElement toImport = XElement.Parse(Content);
                if (toImport.Name == "Announcements")
                {
                    this.ImportAnnouncements(ModuleID, toImport);
                }
                else if (toImport.Name != "heroldit.news")
                    throw new ArgumentException("The element to import is not a valid heroldit.news export.", "Content");

                toImport.Elements("newsEntry")
                    .All(e =>
                             {
                                 NewsEntry entry = NewsEntry.Import(ModuleID, e);
                                 if (null != entry)
                                 {
                                     DataProvider.Instance.StoreNewsEntry(ModuleID, entry);
                                 }
                                 return true;
                             });
            }
            catch (Exception ex)
            {
                Exceptions.LogException(ex);
            }
        }

        #endregion
    }
}
